using System;
using System.Text;
using Microsoft.SharePoint;
using System.Data;
using System.Xml;
using System.Diagnostics;
using Microsoft.SharePoint.Utilities;

namespace CKS.EBE.WebControls
{
    public class BaseQueryControl : XmlBasedControl
    {
        #region "Query Properties"
        private string _QueryXML = "";
        private string _ViewFieldsXML = "<FieldRef Name='Title'/><FieldRef Name='ID'/><FieldRef Name='Author'/>";
        private string _WebsXML = "<Webs Scope='SiteCollection' />";
        private string _ListsXML = "<Lists BaseType='0'/>";
        private bool _ReplaceQueryTokens;

        public bool ReplaceQueryTokens
        {
            get { return _ReplaceQueryTokens; }
            set { _ReplaceQueryTokens = value; }
        }

        private string _AdditionalViewFields = "";
        private uint _RowLimit = 100;

        public string AdditionalViewFields
        {
            get { return _AdditionalViewFields; }
            set { _AdditionalViewFields = value; }
        }

        public int RowLimit
        {
            get { return (int)_RowLimit; }
            set { _RowLimit = (uint)value; }
        }

        public string QueryXML
        {
            get { return _QueryXML; }
            set { _QueryXML = value; }
        }

        public string ViewFieldsXML
        {
            get { return _ViewFieldsXML; }
            set { _ViewFieldsXML = value; }
        }

        public string WebsXML
        {
            get { return _WebsXML; }
            set { _WebsXML = value; }
        }

        public string ListsXML
        {
            get { return _ListsXML; }
            set { _ListsXML = value; }
        }

        #endregion

        //protected override void OnPreRender(EventArgs e)
        //{
        //    base.OnPreRender(e);
        //    if (!string.IsNullOrEmpty(XmlDataSource)) Document = BuildDocument();
        //}

        protected override XmlDocument BuildDocument()
        {
            var oError = new XmlDocument();
            oError.LoadXml("<Error/>");

            try
            {
                var query = new SPSiteDataQuery {Lists = ListsXML, Query = QueryXML};
                if (ReplaceQueryTokens) query.Query = ReplaceTokens(query.Query);
                query.Webs = WebsXML;
                query.ViewFields = ViewFieldsXML + BuildAdditionalViewFields();
                query.RowLimit = (uint) RowLimit;

                DataTable dataTable = Web.GetSiteData(query);
                dataTable.TableName = "row";

                var dataSet = new DataSet("rows");
                dataSet.Tables.Add(dataTable);

                var oDoc = new XmlDocument();
                oDoc.LoadXml(dataSet.GetXml());
                return oDoc;
            }
            catch (Exception ex)
            {
                Trace.Write(ex);
                oError.DocumentElement.InnerText = ex.Message;
            }

            return oError;
        }

        protected virtual string ReplaceTokens(string p)
        {
            try
            {
                p = p.Replace("[Today]", SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today));
                p = p.Replace("[Now]", SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now));

                DateTime dtMonthStart = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1, 0, 0, 0);

                p = p.Replace("[MonthStart]", SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtMonthStart.AddMinutes(-1)));
                p = p.Replace("[MonthEnd]", SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtMonthStart.AddMonths(1).AddMinutes(-1)));

                if (!string.IsNullOrEmpty(Page.Request["y"]))
                {
                    dtMonthStart = new DateTime(int.Parse(Page.Request["y"]), int.Parse(Page.Request["m"]), 1, 0, 0, 0);
                    p = p.Replace("[UrlMonthStart]", SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtMonthStart.AddMinutes(-1)));
                    p = p.Replace("[UrlMonthEnd]", SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtMonthStart.AddMonths(1).AddMinutes(-1)));
                }

                p = p.Replace("[Q1]", Page.Request["q1"]);
                p = p.Replace("[Q2]", Page.Request["q2"]);
                p = p.Replace("[Q3]", Page.Request["q3"]);
            }
            catch { }

            return p;
        }

        protected virtual string BuildAdditionalViewFields()
        {
            if (!string.IsNullOrEmpty(AdditionalViewFields))
            {
                StringBuilder oResult = new StringBuilder();
    
                string[] arViewFields = AdditionalViewFields.Split(',');
                foreach (string s in arViewFields)
                {
                    string sField = s.Trim();
                    bool bNullable = false;
                    if (sField.StartsWith("^"))
                    {
                        bNullable = true;
                        sField = sField.Substring(1);
                    }

                    if (sField.Length > 0)
                        oResult.Append(string.Format("<FieldRef Name='{0}' {1}/>", sField, (bNullable) ? "Nullable='TRUE'" : ""));
                }

                return oResult.ToString();
            }

            return "";
        }
    }
}
